//https://www.tslang.cn/docs/release-notes/typescript-2.1.html
//cnpm i tslib TypeScript注入了一些辅助函数，如继承_extends、JSX中的展开运算符__assign和异步函数__awaiter
function delay(milliseconds: number = 1000): Promise<void> {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => resolve(), 2000)
    });
}

let p1 = new Promise((resolve, reject) => {
    console.info('start p1');
    delay().then(() => {
        console.info('p1');
        resolve()
    });
});

let p2 = new Promise((resolve, reject) => {
    p1.then(() => delay().then(() => resolve()));
});

p2.then(() => console.info('p2'));
////
async function dramaticWelcome() {
    console.log("Hello");

    for (let i = 0; i < 3; i++) {
        await delay(500);
        console.log("dramaticWelcome");
    }

    console.log("World!");
}

dramaticWelcome();

class Demo {
    public asynCall() {
        dramaticWelcome()
    }

    async ff() {
        console.log("Helloff");

        for (let i = 0; i < 3; i++) {
            await delay(500);
            console.log(".ff");
        }

        console.log("World!ff");
    }
}

let d = new Demo()
d.ff()
d.asynCall()

//http://www.ruanyifeng.com/blog/2015/05/async.html
async function myFunction() {
    try {
        await delay();
    } catch (err) {
        console.log(err);
    }
}

// 另一种写法

async function myFunction1() {
    await delay().catch(function (err){
        console.log(err);
    });
}
async function dbFuc(db) {
    let docs = [{}, {}, {}];
    let promises = docs.map((doc) => db.post(doc));

    let results = await Promise.all(promises);
    console.log(results);
}

// 或者使用下面的写法
async function dbFuc1(db) {
    let docs = [{}, {}, {}];
    let promises = docs.map((doc) => db.post(doc));

    let results = [];
    for (let promise of promises) {
        results.push(await promise);
    }
    console.log(results);
}
